var $mqtt = require("@/common/js/mqttws31.js");
var host = 'ssl.lihezzr1.cn';
var port = 8084; 
var useTLS = true; 
var mqtt;
var _this;
var keepAlive = 10;
var reconnectTimeout = 6000;
var yiyuan = {
	destinationName: 'WillMsg',
	stringPayload: 'hhhh',
	qos: 2,
	retained: false
}
// 登陆成功之前
var num1 = 0;
// 之后
var num2 = 0;
var time = 1000;
var connectFlag = true;
var onceConnect = true;
var username; //username和 Password 签名模式下的设置方法，参考文档 https://help.aliyun.com/document_detail/48271.html?spm=a2c4g.11186623.6.553.217831c3BSFry7
var password;
var message;
// 登陆界面状态
var state1 = true;
var lodingtime = 0;
var heartflag = 0;
var timmer;
var loginval;
var topic;
var onConnectionLost
var onMessageArrived
var userid;
var once = true;
var timer1;
// 判断是否显示新订单弹框
var dingdanflag = false;


var MQTTconnect = function(this_, val, userid1, user, password1) {


	username = user;
	password = password1;
	onceConnect = true;
	connectFlag = true;
	_this = this_;
	loginval = val;
	userid = userid1;
	var groupId = 'GID_WENYUE';
	var clientId = groupId + uni.getStorageSync('token');
	mqtt = new $mqtt.Client(
		host, //MQTT 域名
		port, //WebSocket 端口，如果使用 HTTPS 加密则配置为443,否则配置80
		clientId //客户端 ClientId
	);
	var options = {
		userName: username,
		password: password,
		useSSL: useTLS, //如果使用 HTTPS 加密则配置为 true
		keepAliveInterval: keepAlive,
		timeout: 6,
		cleanSession: true,
		willMessage:yiyuan,
		onSuccess: function() {
			console.log('成功')
			onConnect(val)
		},
		onFailure: function(message) { //连接失败
			console.log(message);

			// setTimeout(() => {
			// 	reContent();
			// }, time);
			uni.showToast({
				title: '网络不稳定,请稍后重试',
				icon: 'none'
			});

			closeConnect();
			_this.$bus.$emit("cleartimer", 1)
			_this.$bus.$emit("cleartimer1", 1)

			_this.$bus.$emit("cleartimern", 1);
			_this.$bus.$emit("cleartimerq", 1);
			clearInterval(timmer);
			uni.reLaunch({
				url: '/pages/login/login'
			})
			setTimeout(() => {
				uni.hideLoading();
			}, 1000)

			console.log('连接失败');

		}
	};
	console.log(clientId, username, password, host, port)
	mqtt.onConnectionLost = onConnectionLost;
	mqtt.onMessageArrived = onMessageArrived;
	mqtt.connect(options);

}
var obj = {

	// 登陆处理
	login: function(arr) {
		lodingtime = 1;
		if (arr[1] == 1) {


			if (state1 == true) {
				uni.switchTab({
					url: '/pages/index/index'
				});

			}
			if (state1 == true || num2 > 2) {
				uni.showToast({
					title: `${arr[2]}`,
					icon: "none"
				})
			}

			timmer = setInterval(function() {
				mqtt.send("heart1", "555;");
			}, 7000);


			state1 = false;
			once = false;
			connectFlag = true;
			onceConnect = true;
			num1 = 0;
			// 之后
			num2 = 0;
			time = 1000;
			once = true;

			var topic = "ZiJinTZ_" + uni.getStorageSync('token');
			mqtt.subscribe(topic, {
				qos: 2
			});
			var topicn = 'CICHAN_' + uni.getStorageSync('token');
			mqtt.subscribe(topicn, {
				qos: 2
			});
			var topic3 = "heart_" + uni.getStorageSync('token');
			console.log(topic);
			mqtt.subscribe(topic3, {
				qos: 2
			});



			uni.hideLoading();


		}
		if (arr[1] == 0) {

			onceConnect = false;
			uni.showToast({
				title: arr[2],
				icon: "none"
			})
			// clearInterval(timer1);
			mqtt.disconnect()
		}
	},
	order: function(arr) {
		console.log(arr)

		if (arr[1] == 1) {
			console.log(_this.ifindex);
			if (_this.ifindex == true) {
				var pages = getCurrentPages();

				var page = pages[pages.length - 1];
				console.log(page.route);
				if (page.route != "pages/index/index" && dingdanflag == false) {
					dingdanflag = true;
					uni.showModal({
						content: `有新订单啦,返回首页？`,
						success: function(res) {
							if (res.confirm) {
								_this.$bus.$emit("tabfw", 1)
								uni.switchTab({
									url: '/pages/index/index'
								});
							} else if (res.cancel) {
								_this.$store.commit("ifindex", false)
								console.log('用户点击取消');
							}
						}
					});

				} else {
					dingdanflag = false;
				}
			}
			console.log(uni.getStorageSync('is_auto'))
			if (uni.getStorageSync('is_auto') * 1 == 1) {
				var data = {
					token: uni.getStorageSync('token'),
					order_id: arr[2]
				};
				_this.$store.dispatch('takeorder', data).then(res => {

					if (res.data.code == 1) {
						var data = {
							token: uni.getStorageSync('token'),
						};
						_this.$store.dispatch('orderunderway', data)
					}
				});
			}

			_this.$store.commit("orderadd", arr)

		}

	},
	startorder: function(arr) {
		uni.showToast({
			title: arr[2],
			icon: "none"
		})
		if (arr[1] == 1) {
			_this.$bus.$emit("ifstart", false)
		}
	},
	stoporder: function(arr) {
		uni.showToast({
			title: arr[2],
			icon: "none"
		})
		if (arr[1] == 1) {
			_this.$bus.$emit("ifstart", true)
		}
	},
	heart: function(arr) {
		console.log(arr)
		if (arr[1] == 1) {
			heartflag = 1;
		}
	},
	qiangxx: function(arr) {
		uni.showToast({
			title: arr[2],
			icon: "none"
		})
	},
	assets: function(arr) {

		_this.$store.commit("assetsupdate", arr)
	},
	// 重复登陆
	reLogin: function(arr) {

		closeConnect();
		uni.showModal({
			title: '异地登陆',
			content: `您的帐号已在异地登陆,如果非本人登陆请尽快修改密码!`,
			showCancel: false,
			success: function(res) {
				closeConnect();
				uni.removeStorage({
					key: 'password',
					success: function(res) {

					}
				});
				_this.$bus.$emit("cleartimer", 1)
				_this.$bus.$emit("cleartimer1", 1)
				_this.$bus.$emit("cleartimern", 1);
				_this.$bus.$emit("cleartimerq", 1);
				clearInterval(timmer);
				uni.reLaunch({
					url: '/pages/login/login'
				});
			}
		});
	},
}

onMessageArrived = function(message) {

	var arr = [];
	arr = message.payloadString.split(";");
	console.log(arr);
	switch (arr[0] * 1) {
		case 1:
			obj.order(arr);
			break;
		case 2:
			obj.assets(arr);
			break;
		case 20:
			obj.login(arr);
			break;
		case 21:
			obj.startorder(arr);
			break;
		case 22:
			obj.stoporder(arr);
			break;
		case 23:
			obj.qiangxx(arr);
			break;
		case 51:
			obj.reLogin(arr);
			break;
		case 50:
			obj.heart(arr);
			break;
	}


}

function onConnect(val) { //连接成功
	console.log("连接成功")
	//订阅消息
	lodingtime = 0;


	var topic = "login_" + uni.getStorageSync('token');
	console.log(topic);
	mqtt.subscribe(topic, {
		qos: 2
	});

	console.log(val);
	//测试消息推
	mqtt.send("login_req", val);
	setTimeout(() => {
		if (lodingtime == 0) {

			closeConnect();
			state1 = true;
			uni.reLaunch({
				url: '/pages/login/login'
			});
			var data = {
				token: uni.getStorageSync('token')
			}
			_this.$store.dispatch("logout", data)
			_this.$bus.$emit("cleartimer", 1)
			_this.$bus.$emit("cleartimer1", 1)
			_this.$bus.$emit("cleartimern", 1);
			_this.$bus.$emit("cleartimerq", 1);
			clearInterval(timmer);
			uni.showToast({
				title: "登陆失败，请重新登录",
				icon: "none"
			})

		}
	}, 5000)


}


function closeConnect() {
	connectFlag = false;
	state1 = true;
	clearInterval(timmer);
	// clearInterval(timer1);
	mqtt.disconnect()


}

function reContent() {
	// mqtt.disconnect()
	console.log(num2)
	if (num2 == 2) {
		uni.showToast({
			title: '与服务器断开连接，正在重连...',
			icon: "none",
			mask: true,
			duration: 10000000
		})
	}
	onceConnect = true;
	console.log("重连")
	if (state1) {
		num1++;
	} else {
		if (time > 3000) {
			time = 3000;
		} else {
			time += 1000;
		}

		num2++;
	}
	if (num2 == 4) {
		uni.showToast({
			title: '连接接失败,请重新登录',
			icon: 'none'
		});

	}
	if (num2 > 4) {

		closeConnect();
		state1 = true;
		uni.reLaunch({
			url: '/pages/login/login'
		});
		var data = {
			token: uni.getStorageSync('token')
		}
		_this.$store.dispatch("logout", data)
		clearInterval(timmer);
		_this.$bus.$emit("cleartimer", 1)
		_this.$bus.$emit("cleartimer1", 1)
		_this.$bus.$emit("cleartimern", 1);
		_this.$bus.$emit("cleartimerq", 1);

	}
	//  $mqtt = require("@/common/js/mqttws31.js");
	// $crypto = require("@/common/js/crypto-js.js");
	var groupId = 'GID_WENYUE';
	var clientId = groupId + uni.getStorageSync('token');
	mqtt = new $mqtt.Client(
		host, //MQTT 域名
		port, //WebSocket 端口，如果使用 HTTPS 加密则配置为443,否则配置80
		clientId //客户端 ClientId
	);
	var options = {
		userName: username,
		password: password,
		useSSL: useTLS, //如果使用 HTTPS 加密则配置为 true
		keepAliveInterval: keepAlive,
		timeout: 6,
		onSuccess: function() {
			console.log('连接成功');
			onceConnect = true;
			connectFlag = true;
			uni.hideLoading();
			onConnect(loginval)
		},
		onFailure: function(message) { //连接失败
			console.log(message);
			mqtt.disconnect()
			console.log('连接失败')
			if (connectFlag && onceConnect) {
				setTimeout(() => {
					reContent();
				}, 5000);
			}

		}
	};
	console.log(clientId, username, password, host, port)
	mqtt.onConnectionLost = onConnectionLost;
	mqtt.onMessageArrived = onMessageArrived;
	mqtt.connect(options);

}

function oncereContent() {
	mqtt.disconnect()
	var groupId = 'GID_WENYUE';
	var clientId = groupId + uni.getStorageSync('token');
	mqtt = new $mqtt.Client(
		host, //MQTT 域名
		port, //WebSocket 端口，如果使用 HTTPS 加密则配置为443,否则配置80
		clientId //客户端 ClientId
	);
	var options = {
		userName: username,
		password: password,
		useSSL: useTLS, //如果使用 HTTPS 加密则配置为 true
		keepAliveInterval: keepAlive,
		timeout: 6,
		onSuccess: function() {
			console.log('连接成功');
			onceConnect = true;
			connectFlag = true;
			uni.hideLoading();
			onConnect(loginval)
		},
		onFailure: function(message) { //连接失败
			console.log(message);
			uni.showToast({
				title: '重连失败,请重新登录',
				icon: 'none'
			});
			closeConnect();
			state1 = true;
			uni.reLaunch({
				url: '/pages/login/login'
			});
			_this.$bus.$emit("cleartimer", 1)
			_this.$bus.$emit("cleartimer1", 1)
			_this.$bus.$emit("cleartimern", 1)
			_this.$bus.$emit("cleartimerq", 1);
			clearInterval(timmer);
			var data = {
				token: uni.getStorageSync('token')
			}
			_this.$store.dispatch("logout", data)


		}
	};
	console.log(clientId, username, password, host, port)
	mqtt.onConnectionLost = onConnectionLost;
	mqtt.onMessageArrived = onMessageArrived;
	mqtt.connect(options);

}

function sendmsg(topic, val) {
	mqtt.send(topic, val);
	console.log(topic, val)


}

function sendmsgheart(val) {
	console.log(val);
	heartflag = 0;
	mqtt.send("heart", val);
	setTimeout(() => {
		if (heartflag == 0) {
			if (connectFlag && onceConnect) {
				closeConnect();
				console.log('连接失败')
				setTimeout(() => {
					oncereContent();
				}, 10000);
			}

		}

	}, 3000)
	// Set
}

function onConnectionLost(response) {
	clearInterval(timer1);

	if (connectFlag && onceConnect) {
		setTimeout(() => {
			reContent();
		}, 5000);
		console.log("异常掉线，掉线信息为:" + response.errorMessage);
	} else {
		//连接失败,重新连接
		console.log("主动断开:" + response.errorMessage);
	}

};
export {
	MQTTconnect,
	closeConnect,
	sendmsg,
	sendmsgheart
};
